package per.hnvcam.util.console.ssh;

import org.apache.sshd.client.channel.ChannelShell;
import org.apache.sshd.common.SshConstants;
import org.apache.sshd.common.future.CloseFuture;
import org.apache.sshd.common.util.Buffer;

public class NoCloseChannelShell extends ChannelShell {
   private boolean isClosed;

   public NoCloseChannelShell() {
      super();
      isClosed = false;
   }

   @Override
   protected void pumpInputStream() {
      try {
         while (!closeFuture.isClosed() && !isClosed) {
            Buffer buffer = session.createBuffer(SshConstants.Message.SSH_MSG_CHANNEL_DATA, 0);
            buffer.putInt(recipient);
            int wpos1 = buffer.wpos(); // keep buffer position to write data
                                       // length later
            buffer.putInt(0);
            int wpos2 = buffer.wpos(); // keep buffer position for data write
            buffer.wpos(wpos2 + remoteWindow.getPacketSize()); // Make room
            int len = securedRead(in, buffer.array(), wpos2, remoteWindow.getPacketSize()); // read
                                                                                            // data
                                                                                            // into
                                                                                            // buffer
            if (len > 0) {
               buffer.wpos(wpos1);
               buffer.putInt(len);
               buffer.wpos(wpos2 + len);
               remoteWindow.waitAndConsume(len);
               log.debug("Send SSH_MSG_CHANNEL_DATA on channel {}", id);
               session.writePacket(buffer);
            } else {
               Thread.sleep(100);
            }
         }
         sendEof();
      } catch (Exception e) {
         if (!closing) {
            log.info("Caught exception", e);
            close(false);
         }
      }
   }
   
   @Override
   public CloseFuture close(boolean immediately) {
      isClosed = true;
      return super.close(immediately);
   }

}
